using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using System.Windows;
using TxTReader.Core;

namespace TxTReader.Services
{
    /// <summary>
    /// 设置服务
    /// </summary>
    public class SettingsService
    {
        private const string SettingsFileName = "settings.json";
        private AppSettings _settings;

        public SettingsService()
        {
            _settings = LoadSettings();
        }

        public AppSettings Settings => _settings;

        /// <summary>
        /// 加载设置
        /// </summary>
        /// <returns>应用设置</returns>
        private AppSettings LoadSettings()
        {
            try
            {
                if (File.Exists(SettingsFileName))
                {
                    var json = File.ReadAllText(SettingsFileName);
                    return JsonSerializer.Deserialize<AppSettings>(json) ?? new AppSettings();
                }
            }
            catch
            {
                // 忽略错误，返回默认设置
            }

            return new AppSettings();
        }

        /// <summary>
        /// 保存设置
        /// </summary>
        public async Task SaveSettingsAsync()
        {
            try
            {
                var json = JsonSerializer.Serialize(_settings, new JsonSerializerOptions { WriteIndented = true });
                await File.WriteAllTextAsync(SettingsFileName, json);
            }
            catch (Exception ex)
            {
                throw new SettingsException($"保存设置失败: {ex.Message}", ex);
            }
        }

        /// <summary>
        /// 更新设置
        /// </summary>
        /// <param name="newSettings">新设置</param>
        public async Task UpdateSettingsAsync(AppSettings newSettings)
        {
            System.Diagnostics.Debug.WriteLine($"SettingsService.UpdateSettingsAsync: 更新设置 - 字体:{newSettings.DefaultFontFamily}, 大小:{newSettings.DefaultFontSize}, 缓存:{newSettings.CacheSize}");
            
            _settings = newSettings;
            await SaveSettingsAsync();
            
            System.Diagnostics.Debug.WriteLine($"SettingsService.UpdateSettingsAsync: 设置已更新并保存");
        }
    }

    /// <summary>
    /// 历史记录服务
    /// </summary>
    public class HistoryService
    {
        private const string HistoryFileName = "history.json";
        private readonly List<FileHistoryItem> _history;
        private readonly int _maxHistoryItems = 50;

        public HistoryService()
        {
            _history = LoadHistory();
        }

        public IReadOnlyList<FileHistoryItem> History => _history.AsReadOnly();

        /// <summary>
        /// 加载历史记录
        /// </summary>
        /// <returns>历史记录列表</returns>
        private List<FileHistoryItem> LoadHistory()
        {
            try
            {
                if (File.Exists(HistoryFileName))
                {
                    var json = File.ReadAllText(HistoryFileName);
                    var items = JsonSerializer.Deserialize<List<FileHistoryItem>>(json);
                    return items ?? new List<FileHistoryItem>();
                }
            }
            catch
            {
                // 忽略错误，返回空列表
            }

            return new List<FileHistoryItem>();
        }

        /// <summary>
        /// 保存历史记录
        /// </summary>
        private async Task SaveHistoryAsync()
        {
            try
            {
                var json = JsonSerializer.Serialize(_history, new JsonSerializerOptions { WriteIndented = true });
                await File.WriteAllTextAsync(HistoryFileName, json);
            }
            catch (Exception ex)
            {
                throw new HistoryException($"保存历史记录失败: {ex.Message}", ex);
            }
        }

        /// <summary>
        /// 添加文件到历史记录
        /// </summary>
        /// <param name="filePath">文件路径</param>
        public async Task AddFileAsync(string filePath)
        {
            if (string.IsNullOrEmpty(filePath))
                return;

            // 检查文件是否已存在于历史记录中
            var existingItem = _history.Find(item => item.FilePath.Equals(filePath, StringComparison.OrdinalIgnoreCase));
            
            if (existingItem != null)
            {
                // 如果文件已存在，只更新最后打开时间，保持原有的行号
                existingItem.LastOpened = DateTime.Now;
                // 将现有记录移到开头
                _history.Remove(existingItem);
                _history.Insert(0, existingItem);
            }
            else
            {
                // 如果文件不存在，添加新记录
                _history.Insert(0, new FileHistoryItem
                {
                    FilePath = filePath,
                    FileName = Path.GetFileName(filePath),
                    LastOpened = DateTime.Now,
                    LineNumber = 1 // 默认从第1行开始
                });
            }

            // 限制历史记录数量
            if (_history.Count > _maxHistoryItems)
            {
                _history.RemoveRange(_maxHistoryItems, _history.Count - _maxHistoryItems);
            }

            await SaveHistoryAsync();
        }

        /// <summary>
        /// 更新文件行号
        /// </summary>
        /// <param name="filePath">文件路径</param>
        /// <param name="lineNumber">行号</param>
        public async Task UpdateLineNumberAsync(string filePath, int lineNumber)
        {
            var item = _history.Find(h => h.FilePath.Equals(filePath, StringComparison.OrdinalIgnoreCase));
            if (item != null)
            {
                item.LineNumber = lineNumber;
                item.LastOpened = DateTime.Now;
                await SaveHistoryAsync();
            }
        }

        /// <summary>
        /// 获取文件的历史记录行号
        /// </summary>
        /// <param name="filePath">文件路径</param>
        /// <param name="totalLines">文件总行数</param>
        /// <returns>历史记录的行号，如果无效则返回1</returns>
        public int GetHistoryLineNumber(string filePath, int totalLines)
        {
            var item = _history.Find(h => h.FilePath.Equals(filePath, StringComparison.OrdinalIgnoreCase));
            if (item != null)
            {
                // 验证行号是否有效
                if (item.LineNumber > 0 && item.LineNumber <= totalLines)
                {
                    return item.LineNumber;
                }
            }
            return 1; // 默认返回第1行
        }

        /// <summary>
        /// 清除历史记录
        /// </summary>
        public async Task ClearHistoryAsync()
        {
            _history.Clear();
            await SaveHistoryAsync();
        }

        /// <summary>
        /// 移除特定文件的历史记录
        /// </summary>
        /// <param name="filePath">文件路径</param>
        public async Task RemoveFileAsync(string filePath)
        {
            _history.RemoveAll(item => item.FilePath.Equals(filePath, StringComparison.OrdinalIgnoreCase));
            await SaveHistoryAsync();
        }

        /// <summary>
        /// 更新文件的编码信息
        /// </summary>
        /// <param name="filePath">文件路径</param>
        /// <param name="encoding">编码</param>
        public async Task UpdateFileEncodingAsync(string filePath, System.Text.Encoding encoding)
        {
            var item = _history.Find(h => h.FilePath.Equals(filePath, StringComparison.OrdinalIgnoreCase));
            if (item != null)
            {
                item.Encoding = EncodingDetector.GetEncodingDisplayName(encoding);
                await SaveHistoryAsync();
            }
        }

        /// <summary>
        /// 获取文件的历史记录编码
        /// </summary>
        /// <param name="filePath">文件路径</param>
        /// <returns>历史记录的编码，如果不存在则返回null</returns>
        public string? GetHistoryEncoding(string filePath)
        {
            var item = _history.Find(h => h.FilePath.Equals(filePath, StringComparison.OrdinalIgnoreCase));
            return item?.Encoding;
        }
    }

    /// <summary>
    /// 应用设置
    /// </summary>
    public class AppSettings
    {
        // 字体设置
        public string DefaultFontFamily { get; set; } = "Consolas";
        public double DefaultFontSize { get; set; } = 12;
        public string DefaultForegroundColor { get; set; } = "#000000";
        public string DefaultBackgroundColor { get; set; } = "#FFFFFF";
        
        // 自动换行设置
        public WordWrapMode WordWrapMode { get; set; } = WordWrapMode.None;
        public int WrapLength { get; set; } = 80;
        
        // 编码设置
        public string SelectedEncoding { get; set; } = "Auto"; // 默认自动选择
        
        // 主题设置
        public string CurrentTheme { get; set; } = "Classic"; // 默认经典主题
        
        // 缓存设置
        public int CacheSize { get; set; } = 1000;
        public int PreloadPagesBefore { get; set; } = 2;
        public int PreloadPagesAfter { get; set; } = 3;
        
        // 显示设置
        public bool ShowLineNumbers { get; set; } = false;
        public bool EnableSearchHighlight { get; set; } = true;
        
        // 状态栏设置
        public bool ShowFileName { get; set; } = true;
        public bool ShowTotalLines { get; set; } = true;
        public bool ShowVisibleLines { get; set; } = true;
        public bool ShowLoadedRange { get; set; } = true;
        
        // 其他设置
        public bool EnableHistory { get; set; } = true;
        public bool CloseAfterGoTo { get; set; } = false; // 跳转后关闭窗口
        
        // 兼容性属性（保留旧版本支持）
        public string DefaultEncoding { get; set; } = "UTF-8";
        public int MaxCacheSize { get; set; } = 100;
        public int ChunkSize { get; set; } = 1000;
        public TextWrapping WordWrap { get; set; } = TextWrapping.Wrap;
        public double WrapWidth { get; set; } = 0;
    }

    public enum WordWrapMode
    {
        None,           // 不自动换行
        Window,         // 按窗口自动换行
        Character       // 按指定字数自动换行
    }

    /// <summary>
    /// 文件历史记录项
    /// </summary>
    public class FileHistoryItem
    {
        public string FilePath { get; set; } = string.Empty;
        public string FileName { get; set; } = string.Empty;
        public DateTime LastOpened { get; set; }
        public int LineNumber { get; set; } = 1; // 最后阅读的行号，默认为第1行
        public string Encoding { get; set; } = "UTF-8"; // 最后使用的编码，默认为UTF-8
    }

    /// <summary>
    /// 设置异常
    /// </summary>
    public class SettingsException : Exception
    {
        public SettingsException(string message) : base(message) { }
        public SettingsException(string message, Exception innerException) : base(message, innerException) { }
    }

    /// <summary>
    /// 历史记录异常
    /// </summary>
    public class HistoryException : Exception
    {
        public HistoryException(string message) : base(message) { }
        public HistoryException(string message, Exception innerException) : base(message, innerException) { }
    }
}
